package com.ebelter.bodyfatscale.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.moudules.db.Daos;
import com.ebelter.bodyfatscale.moudules.db.beans.UsersData;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.StatusBarUtil;
import com.ebelter.bodyfatscale.util.ToastUtil;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.btlibrary.btble.impl.scale.model.ScaleUser;
import com.ebelter.btlibrary.util.SpUtil;
import com.ebelter.btlibrary.util.ULog;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity {
    private final String TAG = "LoginActivity";

    @BindView(R.id.et_name_login)
    EditText et_name_login;

    @BindView(R.id.et_pwd_login)
    EditText et_pwd_login;

//    @BindView(R.id.login_mypsw_cb)
//    MyPswEd login_mypsw_cb;


    @Override
    protected int loadLayoutById() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {

        StatusBarUtil.setTranslucent(this, 0);

    }

    @Override
    protected void initData() {
        long user_id = UserSpUtil.readLong(Constants.IUser.USER_ID, -1);
        String nick_name = UserSpUtil.readString(Constants.IUser.NICK_NAME);
        String btid = UserSpUtil.readString(Constants.IUser.BT_ID);

        Constants.isKgUnit = SpUtil.readBoolean(Constants.IUser.IS_KG_MODEL, true);

        ULog.i(TAG, "----LoginActivity---A" + user_id);

        if (user_id > 0 && !TextUtils.isEmpty(nick_name) && !TextUtils.isEmpty(btid)) {
            //说明已经登录了 直接登录吧
            startActivity(MainActivity.class);
            finish();
        }
    }


    @OnClick({R.id.btn_login, R.id.ll_facebook, R.id.ll_twitter, R.id.ll_line, R.id.tv_forgot_password, R.id.tv_join_us_free})
    public void btClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login://sign_in 登录
                sign_in();
                break;
            case R.id.tv_forgot_password://忘记密码
                startActivity(FindPswActivity.class);
                break;
            case R.id.ll_facebook:
                ULog.i(TAG, "----------facebook");
                //StatusBarUtil.setTranslucent(this, 0);
                //StatusBarUtil.setDarkStatusIcon(this,true);
                break;
            case R.id.ll_twitter:
                ULog.i(TAG, "----------twitter");
                Intent intentw = new Intent(LoginActivity.this, CeshiActivity.class);
                startActivity(intentw);

                break;
            case R.id.ll_line:
                Intent intent = new Intent(LoginActivity.this, ModifyActivity.class);
                intent.putExtra(ModifyActivity.MODIFY_STYLE, ModifyActivity.MODIFY_NAME);
                intent.putExtra(ModifyActivity.DISPLAY_VALUE, "测试值");
                startActivity(intent);
                break;
            case R.id.tv_join_us_free:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
        }


    }

    //登录
    private void sign_in() {
        String name = et_name_login.getText().toString().trim();
        String psw = et_pwd_login.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            ToastUtil.show(R.string.Nikename_cannot_be_empty);
            return;
        }
        if (TextUtils.isEmpty(psw)) {
            ToastUtil.show(R.string.The_password_cannot_be_empty);
            return;
        }
        UsersData usersData = Daos.getInstance().getUsersData(name, psw);
        if (usersData == null) {
            if (Daos.getInstance().isExistence(name)) {
                ToastUtil.show(R.string.psw_error);
            } else {
                ToastUtil.show(R.string.mail_nickname_no_exist);
            }
        } else {
            SpUtil.writeLong(Constants.IUser.OPEN_APP_TIME, System.currentTimeMillis());//记录一下打开软件的时间
            saveUserDatas(usersData);
            startActivity(MainActivity.class);
            finish();
        }

    }


    public static String userid2btid(long user_id) {
        if (user_id < 0) {
            user_id = 0;
        }
        String userid = user_id + "";
        if (userid.length() > 14) {
            userid = userid.substring(userid.length() - 14, userid.length());
        }
        return userid;
    }


    //保存登录用户数据
    private void saveUserDatas(UsersData usersData) {
        UserSpUtil.removeAll();

        ULog.i(TAG, "----------" + usersData.toString());

        long useridlong = usersData.userID;
        UserSpUtil.writeLong(Constants.IUser.USER_ID, useridlong);

        // TODO: 2018/4/23 zcq
        String btId = ScaleUser.getUser().toBtId(userid2btid(useridlong));
        ULog.i(TAG, "-----loginSave--useridlong = " + useridlong);
        ULog.i(TAG, "-----loginSave--btId = " + btId);

        UserSpUtil.writeString(Constants.IUser.BT_ID, btId);
        UserSpUtil.writeString(Constants.IUser.NICK_NAME, usersData.name);
        UserSpUtil.writeInt(Constants.IUser.HEIGHT, usersData.height);

        UserSpUtil.writeFloat(Constants.IUser.WEIGHT, usersData.weight);
        //这个体重是服务器的 单位永远是kg

        String birthday = usersData.birthday;
        UserSpUtil.writeString(Constants.IUser.BIRTHDAY, birthday);

        int year = getBirthdayIntValue(birthday, 0, 1990);
        UserSpUtil.writeInt(Constants.IUser.YEAR, year);
        UserSpUtil.writeInt(Constants.IUser.MONTHS, getBirthdayIntValue(birthday, 1, 6));
        UserSpUtil.writeInt(Constants.IUser.DAY, getBirthdayIntValue(birthday, 2, 1));
        UserSpUtil.writeInt(Constants.IUser.AGE, getAgeByBirthday(year));


        UserSpUtil.writeInt(Constants.IUser.SEX, usersData.sex);
        UserSpUtil.writeInt(Constants.IUser.PROFESSION, usersData.profession);
        UserSpUtil.writeFloat(Constants.IUser.IMPEDANCE, usersData.impedance);
//        UserSpUtil.writeString(Constants.IUser.CREATEDATE,resultData.getCreateDate());
//        UserSpUtil.writeString(Constants.IUser.UPDATEDATE,resultData.getUpdateDate());
        UserSpUtil.writeFloat(Constants.IUser.TARGET_WEIGHT, usersData.targetWeight);


    }

    private int getAgeByBirthday(int year) {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR) - year;
    }

    private int getBirthdayIntValue(String string, int index, int defaultValue) {
        if (TextUtils.isEmpty(string)) {
            return defaultValue;
        }
        String[] args = string.split("-");
        if (args.length != 3) {
            return defaultValue;
        }
        return NumUtils.string2Int(args[index], defaultValue);
    }


}
